import { observable, action, computed, autorun } from 'mobx';

class TodoStore {
    constructor () {
        autorun(() => {
            window.localStorage.setItem('todos', JSON.stringify(this.todos))
        }, {
            delay: 500
        })
    }
    // todo 列表
    @observable todos = JSON.parse(window.localStorage.getItem('todos') || '[]')

    // 筛选条件
    @observable filter = 'All'
    // 添加任务
    @action.bound todoAdd (taskName) {
        this.todos.push({
            taskName,
            isCompleted: false
        })
    }
    // 删除任务
    @action.bound todoDelete (index) {
        this.todos.splice(index, 1)
    }
    // 更改任务的是否已完成状态
    @action.bound changeCompleted (index, flag) {
        this.todos[index].isCompleted = flag
    }
    // 计算未完成任务数量
    @computed get unfinishedTodoCount () {
        return this.todos.filter(todo => !todo.isCompleted).length
    }
    // 更改筛选条件
    @action.bound changeFilter (condition) {
        this.filter = condition
    }
    // 监听筛选条件的变化  根据筛选条件对任务进行筛选
    @computed get filterTodo () {
        switch (this.filter) {
            case 'All':
                return this.todos
                break;
            case 'Active':
                return this.todos.filter(todo => !todo.isCompleted)
            case 'Completed':
                return this.todos.filter(todo => todo.isCompleted)
        }
    }
    // 删除所有的已完成任务
    @action.bound clearCompleted () {
        this.todos = this.todos.filter(todo => !todo.isCompleted)
    }
}

const todo = new TodoStore();

export default todo;